package com.ytf.dogbox.dogHttp;

import static com.ytf.dogbox.util.TestConfig.HOST;
import static com.ytf.dogbox.util.TestConfig.httpheader;
import static java.lang.Thread.currentThread;

import com.ytf.dogbox.bean.DownloadItem;
import com.ytf.dogbox.db.SqliteManager;
import com.ytf.dogbox.util.Log;
import com.ytf.dogbox.util.TestConfig;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CountDownLatch;


/**
 * @author tiwolf_li
 * @Date on 2020/6/23
 * @Description  Get方法  主要用来将文件上传到我司的服务器里面
 */
public class DownLoadFile implements Runnable {

    public String TAG="tiwolf";

    private OnThreadResultListener listener;//任务线程回调接口
    private DownloadItem downloadItem;
    SqliteManager sqliteManager;
    File file;

    CountDownLatch downLatch;

    public static boolean forceFlag=false;


    int mFinished=0;



    public DownLoadFile(File file, SqliteManager sqliteManager, CountDownLatch downLatch, DownloadItem downloadItem, OnThreadResultListener listener){
        this.downloadItem=downloadItem;
        this.listener=listener;
        this.downLatch=downLatch;
        this.sqliteManager=sqliteManager;
        this.file=file;
    }


    /**
     * 下载标志：1，表示文件未下载（当前未在下载）；2，表示已经下载完成；3，表示文件正在下载（避免多次下载）
     */
    @Override
    public void run() {
        Log.e(TAG, "run66666: "+currentThread().getName() );
//        String urlStr= TestConfig.downloadFile+downloadItem.getDownloadMd5();
        String urlStr= httpheader+ HOST+ TestConfig.downloadFile+downloadItem.getDownloadMd5();
        String startLength=downloadItem.getDownloadLength();
        sqliteManager.updateDownloadFlag(3,downloadItem.getDownloadMd5());

        Log.e("startplay", "更新了下载标志；"+downloadItem.getDownloadMd5()+"开始下载文件,进度为："+startLength);
        //这里直接进行数据更新。更新下载进度
        RandomAccessFile raf=null;
        HttpURLConnection con=null;
        InputStream is=null;
        try {
//            Log.e(TAG, "download:4未下载的文件下载开始 "+startLength );
            URL url=new URL(urlStr);
            con= (HttpURLConnection) url.openConnection();
            con.setReadTimeout(30000);
            con.setConnectTimeout(30000);
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestMethod("GET");
            con.setRequestProperty("RANGE","bytes="+startLength+"-");
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("Content-Type", "com/ytf/dogbox/application/json");
            //设置下载位置
            int start=Integer.valueOf(downloadItem.getDownloadLength());
            mFinished=start;
//            con.setRequestProperty("Range", "bytes=" + start + "-" + downloadItem.getDownloadEnd());
            //设置一个文件写入位置
            raf=new RandomAccessFile(file,"rwd");
            //设置文件写入位置
            raf.seek(start);

//            Log.e(TAG, "run: 开始下载文件,当前进度为："+mFinished);
//            Log.e(TAG, downloadItem.getDownloadMd5()+"得到的返回值为"+con.getResponseCode() );
            //开始下载
            if (con.getResponseCode()==HttpURLConnection.HTTP_OK){
                //读取数据
                is=con.getInputStream();
                byte[] buffer=new byte[1024*512];
                int len=-1;
                while ((len=is.read(buffer))!=-1){
                    //写入文件
                    raf.write(buffer,0,len);
                    start+=len;
                    mFinished=start;
                    if (forceFlag){
                        Log.e(TAG, "run: 如果遇到设备格式化，或者其他需要强制退出写入文件情况使用");
                        break;
                    }
//                    Log.e(TAG, downloadItem.getDownloadMd5()+"下载文件进度为+mFinish："+mFinished);
                }

//                Log.e(TAG, downloadItem.getDownloadMd5()+"文件已下载完："+mFinished);
                if (!forceFlag){
                    //正常情况下
                    listener.onDownloadFinish();
                    sqliteManager.updateDownloadLength(""+start,2,downloadItem.getDownloadMd5());
                }else {
                    //如果出现强制停止下载的情况下，则记录一下当前下载的进度
                    listener.downloadFailed();
                    sqliteManager.updateDownloadLength(""+mFinished,1,downloadItem.getDownloadMd5());
                }


            }else {
                //说明数据出错，则应该变回未下载
                sqliteManager.updateDownloadFlag(1,downloadItem.getDownloadMd5());
            }

        } catch (Exception e) {
            e.printStackTrace();
//            listener.onDownloadInterrupted();
//            Log.e(TAG, downloadItem.getDownloadMd5()+"文件下载异常，mFinish："+mFinished);
            listener.downloadFailed();
            sqliteManager.updateDownloadLength(""+mFinished,1,downloadItem.getDownloadMd5());
        }finally {
//            Log.e(TAG, "已经全部结束："+mFinished);
            try {
                if (con!=null){
                    con.disconnect();
                }
                if (raf!=null){
                    raf.close();
                }
                if (is!=null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        downLatch.countDown();
    }
}
